# /*
#  * @Author: mikey.zhaopeng 
#  * @Date: 2023-04-19 13:22:56 
#  * @Last Modified by:   mikey.zhaopeng 
#  * @Last Modified time: 2023-04-19 13:22:56 
#  */

#coding: utf8

# 从flask框架中导入Flask类
import os
from flask import Flask, render_template, request, redirect, json, session
from flask_script import Manager
from constants import DB_URI
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from flask_session import Session
import record as rec
import recogation
import hashlib
import ast
hl = hashlib.md5()
#连接数据库
engine = create_engine(DB_URI,echo=True)

Base = declarative_base(engine)

Session = sessionmaker(bind=engine)
sessions = Session()
# 传入__name__初始化一个Flask实例
app = Flask(__name__)
app.debug = True

# manager 管理工具
manager = Manager(app)
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SECRET_KEY'] = os.urandom(24)
# Session(app)


# 初始化棋盘
global map
map = [[0 for i in range(20)] for j in range(20)]

# 创建用户类
class User(Base):
    __tablename__='users'
    # 将id设置为主键，并且默认是自增长的
    id = Column(Integer, primary_key=True)
    # name字段，字符类型，最大的长度是50个字符
    name = Column(String(50))
    fullname = Column(String(50))
    password = Column(String(100))
    
    # 让打印出来的数据更好看，可选的
    def __repr__(self):
        return "<User(id='%s',name='%s',fullname='%s',password='%s')>" % (self.id, self.name, self.fullname, self.password)
# 创建地图类
class Map(Base):
    __tablename__ = 'user_records'
    name = Column(String(50), primary_key=True)
    map_str = Column(String(1000))
    def __repr__(self):
        return "<Map(name='%s',map_str='%s')>" % (self.name, self.map_str)
Base.metadata.create_all()

# app.route装饰器映射URL和执行的函数。这个设置将根URL映射到了hello_world函数上

@app.before_request
def before():
    url = request.path
    # print(url)
    # 白名单
    passUrls = ["/login/", "/register/", "/", "/exit/", "/verify/"]
    suffix = url.endswith('.png') or url.endswith('.jpg') or url.endswith('.css') or url.endswith('.js')
    if url in passUrls or suffix:
        pass
    else:
        user = session.get("user",None)
        # print(username)
        if not user:
            return redirect("/")
        else:
            pass
@app.route("/verify/",methods=['POST'])
def verify_func():
    r = rec.GenAudio()
    r.read_audio()
    r.save_wav("./templates/test.wav")
    text = json.loads(recogation.get_func())
    print(text,text["result"][0])
    res_str = text["result"][0]
    nums = ["零","一","二","三","四","五","六","七","八","九","十"]
    vim_c = res_str.find('行')
    vim_r = res_str.find('列') 
    if vim_c == -1 or vim_r == -1:
        return {"code":401,"msg":"识别失败，请重试"}
    print(vim_c, vim_r)
    row = -1
    col = -1
    for i in range(0,11):
        if nums[i] == res_str[vim_c-1]:
            col = i
            break
    for i in range(0,11):
        if nums[i] == res_str[vim_r-1]:
            row = i
            break
    if row !=-1 and col != -1:
        print(col, row)
        return {"code":200,"col":col,"row":row}
    else :
        if col == -1:
            col = (int(res_str[vim_c-1]))+(int(res_str[vim_c-2]))*10
        if row == -1:
            # print(int(res_str[vim_r-1]), int(res_str[vim_r-2]))
            row = (int(res_str[vim_r-1]))+(int(res_str[vim_r-2]))*10
        print(col, row)
        if row !=-1 and col != -1:
            print(col, row)
            return {"code":200,"col":col,"row":row}
        else:
            return {"code":401,"msg":"识别失败，请重试"}
@app.route("/exit/", methods=['POST'])
def exit():
    session.pop("user")
    user = session.get("user", None)
    global map
    map = [[0 for i in range(20)] for j in range(20)]
    # print(user,"111")
    if not user:
        return {"code":200,"msg":"success"}
    else:
        return {"code":201,"msg":"error"}
@app.route('/login/', methods=['GET','POST'])
def login_func():
    # print(2)
    if request.method=='GET':
        return render_template('Login.html')
    # print(request.form['username'],request.form['password'])
    username = request.form['username']
    password = request.form['password']
    hl.update(username.encode(encoding='utf-8'))
    md5_user = hl.hexdigest()
    hl.update(password.encode(encoding='utf-8'))
    md5_password = hl.hexdigest()
    print(md5_user, md5_password)
    userList = sessions.query(User).filter_by(name=username, password=password)
    flag = userList.count()
    # print(flag)
    if flag == 1 :
        session['user'] = {"username":username,"id":userList[0].id}
        # print(userList[0].id)
        return {"code": 200, "msg": {flag:1}}
    else :
        return {"code": 201, "msg": {flag:0}}
@app.route('/register/', methods=['GET','POST'])
def register_func():
    # print(1)
    if request.method=='GET':
        return render_template('Register.html')
    # print(request.form['username'],request.form['password'])
    username = request.form['username']
    password = request.form['password']
    hl.update(username.encode(encoding='utf-8'))
    md5_user = hl.hexdigest()
    hl.update(password.encode(encoding='utf-8'))
    md5_password = hl.hexdigest()
    fullname=username
    print(md5_user, md5_password)
    userList = sessions.query(User).filter_by(name=username)
    flag = userList.count() 
    if flag : 
        return {"code":201,"msg":"用户已存在"}
    else:
        new_uer = User(name=username, 
                       fullname=fullname, 
                       password=password)
        sessions.add(new_uer)
        sessions.commit()
        id = sessions.query(User).filter_by(name=username)[0].id
        session['user'] = {"username":username,"id":id}
        return {"code":200,"msg":"添加成功"}
@app.route('/home/', methods=['GET','POST'])
def home_page():
    return render_template('Home.html')

@app.route('/game/')
def game_page():
    return render_template('Game.html')

@app.route('/returnPre', methods=["POST"])
def returnPre():
    map_str = sessions.query(Map).filter_by(name = session.get("user")["username"])
    # print(map_str[0].map_str,"1")
    return {"code":200,"msg":map_str[0].map_str}

@app.route('/saveRecord', methods=["POST"])
def saveRecord():
    # print(type(map),type(str(map)))
    map_str = str(map)
    # print(type(session.get("user")))
    user = sessions.query(Map).filter_by(name = session.get("user")["username"])
    # print(user)
    print(user.count() )
    flag = user.count()
    if flag > 0:
        user.update({'map_str' : map_str})
        sessions.commit()
        return {"code":200,"msg":"保存成功"}
    else:
        new_record = Map(name = session.get("user")["username"], map_str = map_str)
        sessions.add(new_record)
        sessions.commit()
        return {"code":200,"msg":"保存成功"}

@app.route('/init', methods=["POST"])
def init_func():
    flag = request.form["flag"]
    # print(request.form["flag"])
    global map
    map = [[0 for i in range(20)] for j in range(20)]
    # print(map)
    if flag == 1:
        return {"code":200,"msg":"初始化完成"}
    else:
        return {"code":201,"msg":"清零"}
@app.route('/check', methods=["POST"])
def check_func():
    # print("check")
    flag = int(request.form['flag']) + 1
    # print(flag)
    # 2 黑子下 1 白子下
    tmprow = request.form['row']
    tmpcol = request.form['col']

    row = int(tmprow)
    col = int(tmpcol)
    print(col,row)
    
    total = 1

    map[row][col] = flag
    # print(map)
    chessboard = map

    # 水平方向上的check
    while col - 1 > 0 and chessboard[row][col - 1] == flag:
        total = total + 1
        col = col - 1

    row = int(tmprow)
    col = int(tmpcol)
    while col + 1 < 20 and chessboard[row][col + 1] == flag:
        total = total + 1
        col = col + 1

    if total >= 5:
        if flag == 2:
            return {"code": 201, "msg": "黑棋获胜"}
        else:
            return {"code": 202, "msg": "白棋获胜"}

    # 垂直方向上的check
    row = int(tmprow)
    col = int(tmpcol)
    while row - 1 > 0 and chessboard[row - 1][col] == flag:
        total = total + 1
        row = row - 1

    row = int(tmprow)
    col = int(tmpcol)
    while row + 1 < 20 and chessboard[row + 1][col] == flag:
        total = total + 1
        row = row + 1

    if total >= 5:
        if flag == 2:
            return {"code": 201, "msg": "黑棋获胜"}
        else:
            return {"code": 202, "msg": "白棋获胜"}

    # 检查斜边左下右上
    row = int(tmprow)
    col = int(tmpcol)
    while row - 1 > 0 and col + 1 < 20 and chessboard[row - 1][col + 1] == flag:
        total = total + 1
        row = row - 1
        col = col + 1

    row = int(tmprow)
    col = int(tmpcol)
    while row + 1 < 20 and col - 1 > 0 and chessboard[row + 1][col - 1] == flag:
        total = total + 1
        row = row + 1
        col = col - 1

    if total >= 5:
        if flag == 2:
            return {"code": 201, "msg": "黑棋获胜"}
        else:
            return {"code": 202, "msg": "白棋获胜"}
        
    # 检查斜边左上右下
    row = int(tmprow)
    col = int(tmpcol)
    while row - 1 > 0 and col - 1 > 0 and chessboard[row - 1][col - 1] == flag:
        total = total + 1
        row = row - 1
        col = col - 1

    row = int(tmprow)
    col = int(tmpcol)
    while row + 1 < 20 and col + 1 < 20 and chessboard[row + 1][col + 1] == flag:
        total = total + 1
        row = row + 1
        col = col + 1

    if total >= 5:
        if flag == 1:
            return {"code": 201, "msg": "黑棋获胜"}
        else:
            return {"code": 202, "msg": "白棋获胜"}
    return {"code":203,"msg":"继续"}
@app.route('/')
def hello_world():
    return redirect("/login/")

@manager.command
def dev():
    from livereload import Server
    liver_server = Server(app.wsgi_app)
    liver_server.watch("**/*.*")
    liver_server.serve(open_url_delay=True)
if __name__ == '__main__':
    # 运行本项目，host=0.0.0.0可以让其他电脑也能访问到该网站，port指定访问的端口。默认的host是127.0.0.1，port为5000
    # app.run(host='0.0.0.0', port=9000)
    manager.run()
    
